package com.zyk.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.zyk.entity.Role;
import com.zyk.entity.RoleResource;
import com.zyk.entity.User;
import com.zyk.mapper.RoleMapper;
import com.zyk.mapper.RoleResourceMapper;
import com.zyk.service.IRoleService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.zyk.vo.FinalResult;
import com.zyk.vo.RoleVo;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author feifeimao
 * @since 2017-11-20
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleResourceMapper roleResourceMapper;

    /**
     * 根据userid获取所有用户拥有的角色
     * @param userId
     * @return
     */
    public List<Role> selectRoleIdListByUserId(Long userId) {
        return baseMapper.selectRoleIdListByUserId(userId);
    }

    /**
     * 编辑角色
     * @param role
     * @return
     */
    public FinalResult edit(Role role) {

        if( roleMapper.update(role)==1){
            return new FinalResult("编辑成功",true);
        }else {
            return new FinalResult("编辑失败",false);
        }
    }

    /**
     * 获取角色所有resourceId
     * @param role
     * @return
     */
    public FinalResult findResourceIdListByRoleId(Role role) {
        Set<RoleResource> roleResources = roleResourceMapper.findResourceIdListByRoleId(role.getId());
        Set<Long> ids=new HashSet<Long>();
        for (RoleResource rr: roleResources) {
            ids.add(rr.getResourceId());
        }
        return new FinalResult("",ids,true);
    }

    /**
     * 查询所有角色
     * @return
     */
    public List<RoleVo> findAll() {
        List<Role> roles = super.selectList(new EntityWrapper<Role>(null));
        List<RoleVo> roleVos= new ArrayList<RoleVo>();
        for (Role role: roles) {
            RoleVo roleVo= new RoleVo();
            roleVo.setText(role.getName());
            roleVo.setId(role.getId());
            roleVos.add(roleVo);
        }
        return roleVos;
    }
}
